package com.lry;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class Slave {

    private List<Slave> otherSlaves;

    private List<Integer> values;

    public boolean error;

    private String name;

    private Random random;


    public Slave(String name){
        otherSlaves = new ArrayList<>();
        values = new ArrayList<>();
        this.name = name;
        random = new Random();
    }

    public void registerOtherSlave(Slave... slaves){
        for (Slave slave : slaves) {
            if(null==slave){
                continue;
            }
            otherSlaves.add(slave);
        }
    }

    public void receiveFromMaster(Integer value){
        log.info("receiveFromMaster，slave:{}收到value:{}",this,value);
        values.add(value);
        log.info("receiveFromMaster，slave:{}的values:{}",this,values);
        notifyOthers(value);
    }

    private void receiveFromSlave(Integer value){
        log.info("receiveFromSlave，slave:{}收到value:{}",this,value);
        values.add(value);
        log.info("receiveFromSlave，slave:{}的values:{}",this,values);
    }


    private void notifyOthers(Integer value){
        for (Slave otherSlave : otherSlaves) {
            if(error){
                value = random.nextInt(100);
            }
            Integer finalValue = value;
            CompletableFuture.runAsync(()->{
                otherSlave.receiveFromSlave(finalValue);
            });
        }
    }

    @Override
    public String toString() {
        return name;
    }
}
